package net.bxx2004.pandalib.bukkit.item;

import de.tr7zw.changeme.nbtapi.NBTItem;
import net.bxx2004.pandalib.PandaLib;
import net.bxx2004.pandalib.bukkit.listener.PListener;
import org.bukkit.Material;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.Plugin;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public abstract class ItemAbility implements Listener {
    public static List<ItemAbility> abilities = new ArrayList<>();
    public ItemAbility(){
        register();
        if (customListener(PandaLib.initPlugin) != null){
            customListener(PandaLib.initPlugin).hook(PandaLib.initPlugin.getName());
        }
        new PListener(){
            @EventHandler
            public void on(PlayerInteractEvent event){
                if (event.getItem() != null){
                    if (event.getItem().getType() != Material.AIR){
                        PItemStack stack = new PItemStack(event.getItem());
                        if (stack.hasAbility(ItemAbility.get(uuid()))){
                            if (of(stack).uuid().toString().equals(uuid().toString())){
                                onInteract(event);
                            }
                        }
                    }
                }
            }
        }.hook(PandaLib.initPlugin.getName());

    }
    public abstract PListener customListener(Plugin bukkitPlugin);
    public abstract void onInteract(PlayerInteractEvent event);
    public abstract UUID uuid();
    public abstract List<String> lore();
    private void register(){
        abilities.add(this);
    }
    public static ItemAbility of(PItemStack stack){
        NBTItem nbti = new NBTItem(stack);
        if (nbti.hasTag("ability")){
            for (ItemAbility ability : abilities){
                if (ability.uuid().toString().equals(nbti.getCompound("ability").getString("uuid"))){
                    return ability;
                }
            }
        }
        return null;
    }
    public static ItemAbility get(UUID uuid){
        final ItemAbility[] a = new ItemAbility[1];
        abilities.forEach(s ->{
            if (s.uuid().toString().equals(uuid.toString())){
                a[0] = s;
            }
        });
        return a[0];
    }
}
